package com.biwin.core.main.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * TODO
 *
 * @author biwin
 * @since 0.0.1
 */
@RestControllerAdvice(basePackages = {"com.biwin"})
public class RequestControllerAdvice extends RequestBodyAdviceAdapter {
    private static final Logger log = LoggerFactory.getLogger(RequestControllerAdvice.class);
    private final String OPERATION_USER = "operationUser";

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("RequestControllerAdvice#supports");
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                           Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        log.info("RequestControllerAdvice#beforeBodyRead");

        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("RequestControllerAdvice#afterBodyRead");

        try {
            Field operationUser = getOperationUser(body);
            operationUser.setAccessible(true);
            //            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            //            todo 等正常设置权限时,需修改此处
            operationUser.set(body, 1L);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("handleEmptyBody#supports");
        return body;
    }

    private Field getOperationUser(Object body) {
        Field field;
        try {
            if (body instanceof Class) {
                field = ((Class<?>) body).getDeclaredField(OPERATION_USER);
            } else {
                field = body.getClass().getDeclaredField(OPERATION_USER);
            }
        } catch (NoSuchFieldException e) {
            return getOperationUser(body.getClass().getSuperclass());
        }
        return field;
    }
}
